/**
 * 
 */
package fr.cephb.joperon.webapp;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.FilterChain;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import fr.cephb.joperon.webapp.jpa.User;
import fr.cephb.servlet.AbstractFilter;


/**
 * @author lindenb
 * Security Filter
 */
public class SecurityFilter extends AbstractFilter
	{
	@Override
	public void doFilter(ServletRequest xreq, ServletResponse xres,
			FilterChain chain) throws IOException, ServletException
	{
	
		
	HttpServletRequest req=HttpServletRequest.class.cast(xreq);
	HttpServletResponse res=HttpServletResponse.class.cast(xres);
	HttpSession session = req.getSession();
	
	
	
	
	User userBean =User.class.cast(session.getAttribute("operon_user"));
	boolean valid=userBean!=null;
	
	
	
	String path= req.getPathInfo();
	if(path==null) path= req.getServletPath();
	
	if(path!=null &&
			(
			path.equals("/login.jsp") ||
			path.equals("/logout.jsp")
			))
		{
		valid=true;
		}
	
	if(!valid)
		{
		String filterActivated  = getFilterConfig().getInitParameter("enabled");
		if("false".equals(filterActivated))
			{
			valid=true;
			}
		}
	
	
	if(!valid)
		{

		String permissionFile =getFilterConfig().getInitParameter(JOperonConstants.getPermissionFilePath());
		if(permissionFile==null) throw new ServletException("Undefined "+JOperonConstants.getPermissionFilePath());
		String user=req.getParameter("user");
		String password=req.getParameter("password");
		
		if(user!=null && password!=null)
			{
			//userBean = User.findUserByLoginPassword(user, password.getBytes(), new File(permissionFile));
			if(userBean!=null) session.setAttribute(JOperonConstants.getUserSession(), userBean);
			valid=userBean!=null;
			}
		
		}
	
	
	
	if(!valid)
		{
		String requestURI=req.getParameter("requesturi");
		if(requestURI==null) requestURI=req.getRequestURI();
		if(requestURI==null) requestURI="";
		RequestDispatcher ds = getFilterConfig().getServletContext().getRequestDispatcher(
				"/login.jsp?errorMsg=&requesturi="+URLEncoder.encode(requestURI, "UTF-8"));
	    ds.forward(req, res);
		}
	else
		{
	
		chain.doFilter(req, res);
		}
	}

}
